<template>
  <div class="contain">
    <div class="pics">
      <div v-for="(item, index) of showUploads" :key="index" class="pic">
        <img :src="item.url" alt="" />
      </div>
      <!-- <div class="pic">
        <img src="@/assets/logo.png" alt="" />
      </div>
      <div class="pic">
        <img src="@/assets/logo.png" alt="" />
      </div>
      <div class="pic">
        <img src="@/assets/logo.png" alt="" />
      </div> -->
      <div class="picbox" @click="$refs.upload.click()">+</div>
    </div>
    <form action="javascript:;" method="post" ref="uploadForm">
      <input
        type="file"
        name="user-photo"
        ref="upload"
        @change="change"
        style="display: none"
      />
      <button @click="uploadAvatar">上传头像</button>
      <button @click="register">注册</button>
    </form>
  </div>
</template>

<script>
import axios from "axios";
import { reactive, ref } from "vue";
export default {
  name: "UploadPic",
  setup() {
    const instance = axios.create({
      baseURL: "http://home.softeem.xin:9544",
    });
    let uploadForm = ref(null);
    //需要展示图片数组
    let showUploads = reactive([]);
    let uploads=reactive([])

    //当input：file发生改变时触发，在这里进行图片合法性的判断
    function change(e){
        console.log(e.target.files);
        let reg=/^image\/(png|jpg|jpeg)$/
        if(reg.test(e.target.files[0].type) &&e.target.files[0].size<1024*1000){
            showUploads.push({
                url:URL.createObjectURL(e.target.files[0])
            })
            uploads.push({file:e.target.files[0]})
        }else{
            alert('图片不合法')  
        }
    }

    function uploadAvatar(){
        console.log(uploadForm)
        instance.post('/userInfo/uploadUserPhoto',new FormData(uploadForm.value)).then(
            response=>{
                console.log(response.data);
            }
        ).catch(
            error=>{
                console.log(error.message);
            }
        )
    }

    return { uploadForm, showUploads,change,uploads,uploadAvatar };
  },
};
</script>

<style lang="less" scoped>
.contain {
  width: 100vw;
  // height: 100vh;
  height: 602px;
  background-color: skyblue;
  button {
    padding: 5px;
    font-size: 20px;
  }
  .pics {
    width: 100vw;
    display: grid;
    grid-template-rows: repeat(auto-fill, 100px);
    grid-template-columns: repeat(auto-fill, 100px);
    grid-gap: 10px;
    grid-auto-rows: 100px;
    justify-content: center;
    .picbox {
      background-color: lightgray;
      font-size: 50px;
      line-height: 100px;
      text-align: center;
    }
    .pic {
      img {
        width: 100px;
        height: 100px;
        object-fit: cover;
      }
    }
  }
}
</style>
